<template>
	<div ref="chartRef" class="delay-rate-chart"></div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';

interface Props {
	rate: number;
}

const props = defineProps<Props>();

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
let isDestroyed = false;

// 初始化图表
const initChart = () => {
	if (isDestroyed || !chartRef.value) return;
	
	try {
		// 如果已存在实例，先销毁
		if (chartInstance) {
			chartInstance.dispose();
			chartInstance = null;
		}
		
		// 创建新实例
		chartInstance = echarts.init(chartRef.value);
	} catch (error) {
		console.error('DelayRateChart 初始化图表失败:', error);
	}
};

// 渲染图表
const renderChart = () => {
	if (isDestroyed || !chartRef.value || !chartInstance) return;
	
	try {
		const rate = Math.min(props.rate, 100); // 确保不超过100%
		const remaining = 100 - rate;
		
		const option = {
			series: [
				{
					type: 'pie',
					radius: ['60%', '80%'],
					center: ['50%', '50%'],
					startAngle: 90,
					data: [
						{
							value: rate,
							name: '延期率',
							itemStyle: {
								color: getRateColor(rate)
							}
						},
						{
							value: remaining,
							name: '正常率',
							itemStyle: {
								color: '#f0f0f0'
							}
						}
					],
					label: {
						show: false
					},
					labelLine: {
						show: false
					},
					emphasis: {
						scale: false
					}
				}
			],
			graphic: {
				type: 'text',
				left: 'center',
				top: 'center',
				style: {
					text: `${rate.toFixed(1)}%`,
					fontSize: 12,
					fontWeight: 'bold',
					fill: getRateColor(rate)
				}
			}
		};
		
		chartInstance.setOption(option);
	} catch (error) {
		console.error('DelayRateChart 渲染图表失败:', error);
	}
};

// 根据延期率获取颜色
const getRateColor = (rate: number): string => {
	if (rate >= 80) return '#f56c6c'; // 红色 - 严重
	if (rate >= 50) return '#e6a23c'; // 橙色 - 警告
	if (rate >= 20) return '#f093fb'; // 紫色 - 注意
	return '#67c23a'; // 绿色 - 良好
};

// 监听数据变化
watch(() => props.rate, () => {
	nextTick(() => {
		renderChart();
	});
}, { immediate: false });

// 监听窗口大小变化
const handleResize = () => {
	if (chartInstance) {
		chartInstance.resize();
	}
};

onMounted(() => {
	initChart();
	renderChart();
	window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
	isDestroyed = true;
	window.removeEventListener('resize', handleResize);
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
});
</script>

<style lang="scss" scoped>
.delay-rate-chart {
	width: 100%;
	height: 100%;
}
</style> 